package indi.zjh.dp.access;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;



import indi.zjh.dp.util.HttpUtil;

public class Request {
	public static final int GET = 0;
	public static final int POST = 1;
	private int method = POST;
	private HashMap<String, String> params = new HashMap<String, String>();
	
	public static Request create()
	{
		Request req = new Request();
		return req;
	}
	
	public Request method(int m)
	{
		this.method = m;
		return this;
	}
	
	public Request param(String key, String val)
	{
		this.params.put(key, val);
		return this;
	}
	
	public String send(String url)
	{
		String ret = null;
		
		if(this.method == POST)
		{
			ret = HttpUtil.doPost(url, this.params);
		}
		else
		{
			StringBuffer queryStr = new StringBuffer();
			queryStr.append(url);
			
			if(this.params.size() > 0)
			{
				queryStr.append("?");
				String[] strings = new String[this.params.size()];
				int i = 0;
				Iterator<Map.Entry<String, String>> iter = this.params.entrySet().iterator();
				while(iter.hasNext())
				{
					Map.Entry<String, String> entry = iter.next();
					strings[i++] = entry.getKey()+"="+entry.getValue();
				}
				queryStr.append(String.join("&", strings));
			}
			ret = HttpUtil.doGet(queryStr.toString());
		}
		
		return ret;
	}
	
}
